﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Net;
using System.Xml;

namespace Vapeur
{
    public class Video
    {
        public string Title { get; set; }
        public string VideoURL { get; set; }
        public string Filename { get; set; }
        public string Description { get; set; }
        public string YouTubeID { get; set; }
        
        private string youTubeURL;
        private Track track;
        XmlTextReader reader;

        public Track Track
        {
            get { return track; }
            set
            {
                track = value;

                this.Filename = this.track.Artist + " - " + this.track.Name + ".flv";

                readXml();
                //this.VideoURL = this.GetDownloadURL(this.YouTubeID);
            }
        }

        public string YouTubeURL
        {
            get { return youTubeURL; }
            set
            {
                youTubeURL = value;
                this.YouTubeID = youTubeURL.Remove(0, 31);
                this.VideoURL = this.GetDownloadURL(this.YouTubeID);

                if (this.Filename == null)
                {
                    this.Filename = this.Title + ".flv";
                }
            }
        }

        public override string ToString()
        {
            if (this.Track == null)
            {
                return this.Title;
            }

            if (this.Track.SearchType == SearchType.Manual)
            {
                return this.Title;
            }
            return (this.Track.Artist + " - " + this.Track.Name);
        }

        private void readXml()
        {
            string URLString = "http://gdata.youtube.com/feeds/api/videos?vq=" + this.track.Artist + " - " + this.track.Name;

            string currentElement = null;

            try
            {
                reader = new XmlTextReader(URLString);

                while (reader.Read() && (this.YouTubeURL == null))
                {
                    switch (reader.NodeType)
                    {
                        case XmlNodeType.Element: // The node is an element.
                            currentElement = reader.Name;
                            while (reader.MoveToNextAttribute()) // Read the attributes.
                            {
                                if (reader.Name == "href")
                                {
                                    string watch = "http://www.youtube.com/watch?v=";
                                    if (reader.Value.StartsWith(watch))
                                    {
                                        this.YouTubeURL = reader.Value;
                                        break;
                                    }
                                }
                            }
                            break;

                        //case XmlNodeType.Text: //Display the text in each element.
                        //    if (currentElement == "title")
                        //    {
                        //        if (!reader.Value.StartsWith("YouTube Videos matching query"))
                        //        {
                        //            this.Title = reader.Value;
                        //        }
                        //    }
                        //    break;
                    }
                }
            }

            catch (Exception)
            {
                //TODO: Warning!! blackholing exception
            }
        }

        private string GetDownloadURL(string videoId)
        {
            WebClient client = new WebClient();

            //real slow operation, can't be helped.
            string buffer = client.DownloadString("http://www.youtube.com/watch?v=" + videoId);

            int start = 0, end = 0;
            string startTag = "<meta name=\"title\" content=\"";
            string endTag = "\">\n\t<meta name=\"description\" content=";

            start = buffer.IndexOf(startTag, StringComparison.CurrentCultureIgnoreCase);
            end = buffer.IndexOf(endTag, start, StringComparison.CurrentCultureIgnoreCase);

            //This is a hack, throws an exception if end is -1 (no endTag found)
            if (end < 0)
            {
                return null;
            }

            int index = start + startTag.Length;
            if (index < 0)
            {
                index = 0;
            }

            this.Title = buffer.Substring(index, end - start - startTag.Length);

            start = 0;
            end = 0;

            startTag = "\"video_id\":";
            endTag = "\"plid\":";

            start = buffer.IndexOf(startTag, StringComparison.CurrentCultureIgnoreCase);
            end = buffer.IndexOf(endTag, start, StringComparison.CurrentCultureIgnoreCase);

            //This is a hack, throws an exception if end is -1 (no endTag found)
            if (end < 0)
            {
                return null;
            }

            index = start + startTag.Length;
            if (index < 0)
            {
                index = 0;
            }
            string str = buffer.Substring(index, end - start - startTag.Length);
            string[] str1 = str.Split(',');
            string video_id = str1[0].Replace("\"", "");

            string l = str1[1].Replace("\"l\": ", "").Replace("\"", "");
            string sk;
            string t;

            if (str1[2].Contains("\"sk\": "))
            {
                sk = str1[2].Replace("\"sk\": ", "").Replace("\"", "");
            }
            else if (str1[3].Contains("\"sk\": "))
            {
                sk = str1[3].Replace("\"sk\": ", "").Replace("\"", "");
            }
            else
            {
                return null;
            }

            if (str1[4].Contains("\"t\": "))
            {
                t = str1[4].Replace("\"t\": ", "").Replace("\"", "");
            }
            else if (str1[5].Contains("\"t\": "))
            {
                t = str1[5].Replace("\"t\": ", "").Replace("\"", "");
            }
            else
            {
                return null;
            }

            return "http://www.youtube.com/get_video?video_id=" + video_id + "&sk=" + sk + "&t=" + t;
        }
    }
}
